package com.chandon.juc.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程数量固定的线程池FixedThreadPool
 *
 *  构建方式：
 *  public static ExecutorService newFixedThreadPool(int nThreads) {
 *
 *         return new ThreadPoolExecutor(nThreads, nThreads,
 *                                       0L, TimeUnit.MILLISECONDS,
 *                                       new LinkedBlockingQueue<Runnable>());
 *     }
 *
 *  使用ThreadPoolExecutor构建，nThreads为线程池中线程的数量。
 *  线程池中的线程是懒加载的，有任务投递时才会创建线程。
 *  任务会放进无界队列中，等待线程从队列中take出执行。
 *  若投递的任务没有空闲线程处理，便会放入LinkedBlockingQueue无界队列中，等待有空闲线程take出任务执行。
 *
 * @author Dong
 */

public class TestFixedThreadPool {
	public static void main(String[] args) {

		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4,
				new NamedThreadFactory("fixedThreadFactory"));


		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务1"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务2"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务3"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务4"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务5"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务6"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务7"));
		fixedThreadPool.execute(() -> System.out.println(Thread.currentThread().getName() + " 任务8"));

		fixedThreadPool.shutdown();
		/*
		线程1任务1
		线程2任务2
		线程3任务3
		线程4任务4
		线程1任务5
		线程2任务6
		线程3任务7
		线程4任务8
		*/
	}

}
